package com.bishe.psy.service.impl;

import com.bishe.psy.common.AppResult;
import com.bishe.psy.common.ResultCode;
import com.bishe.psy.config.AppConfig;
import com.bishe.psy.dao.ConUserMapper;
import com.bishe.psy.dao.StuUserMapper;
import com.bishe.psy.exception.ApplicationException;
import com.bishe.psy.model.ConUser;
import com.bishe.psy.model.StuUser;
import com.bishe.psy.service.IConUserService;
import com.bishe.psy.utils.MD5Util;
import com.bishe.psy.utils.StringUtil;
import com.bishe.psy.utils.UUIDUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: L
 * Date: 2024-03-28
 * Time: 17:32
 */

@Slf4j
@Service
public class ConUserServiceImpl implements IConUserService {

    @Resource
    private ConUserMapper conUserMapper;

    //根据用户名查询用户
    @Override
    public ConUser ConselectByUsername(String username) {
        if(StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return conUserMapper.ConselectByUsername(username);
    }

    @Override
    public ConUser login(String username, String password) {
        //1.查询用户名是否存在
        ConUser conUser =  ConselectByUsername(username);

        if(conUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //2.密码校验
        String salt = conUser.getSalt();
        String ciphertext = MD5Util.md5(password,salt);

        //输入密码不正确
        if(!ciphertext.equals(conUser.getPassword())) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        return conUser;
    }


    @Override
    public ConUser selectByPrimaryKey(Long id) {

        //参数非空校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //根据id查询
        ConUser conUser = conUserMapper.selectByPrimaryKey(id);

        return conUser;
    }

    @Override
    public void addOneArticleCountById(Long id) {

        //1.参数校验
        if(id == null) {
            log.warn("用户发帖数新增的id为空");
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //2.参数校验通过，根据id查询用户
        ConUser conUser = conUserMapper.selectByPrimaryKey(id);

        //3.判断查询结果是否为空
        if(conUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //4.用户存在，更新用户数据
        ConUser conUser1 = new ConUser();
        conUser1.setId(conUser.getId());

        //文字数量+1即可
        conUser1.setArticleCount(conUser.getArticleCount() + 1);

        //更新到数据库中
        int row = conUserMapper.updateByPrimaryKeySelective(conUser1);

        if(row != 1) {
            log.warn( "更新用户文字文章数" + ResultCode.FAILED );
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }

    @Override
    public void subOneArticleCountById(Long id) {
        //1.参数校验
        if(id == null) {
            log.warn("当前传递用户的id为空");
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //2.参数校验通过，根据id查询用户
        ConUser conUser = conUserMapper.selectByPrimaryKey(id);

        //3.判断查询结果是否为空
        if(conUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //4.用户存在，更新用户数据
        ConUser conUser1 = new ConUser();
        conUser1.setId(conUser.getId());

        //文章数量+1即可
        conUser1.setArticleCount(conUser.getArticleCount() - 1);

        //判断-1之后是否小于0，若为0，则设置为零
        if(conUser1.getArticleCount() < 0 ){
            conUser1.setArticleCount(0);
        }

        //更新到数据库中
        int row = conUserMapper.updateByPrimaryKeySelective(conUser1);

        if(row != 1) {
            log.warn( "更新用户文字文章数" + ResultCode.FAILED );
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyConInfo(ConUser conUser) {
        //1.参数校验
        if(conUser == null || conUser.getId() == null || conUser.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.根据当前id查询用户是是否存在
        ConUser selectConUser = conUserMapper.selectByPrimaryKey(conUser.getId());


        //3.判断当前用户是否存在
        if(selectConUser == null || selectConUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //4.创建一个更新对象
        ConUser updateConUser = new ConUser();
        updateConUser.setId(selectConUser.getId());


        //5.判断是否能够调用更新语句的字段
        boolean flag = false;

        //6.当昵称、邮箱地址、电话号码、咨询师类型,个人简介，存在一个字段被修改，则可以调用数据库修改语句
        //当上述字段都没有被修改时，则不能掉用数据库语句
        if(!StringUtil.isEmpty(conUser.getNickname()) && !conUser.getNickname().equals(selectConUser.getNickname())) {
            updateConUser.setNickname(conUser.getNickname());
            flag = true;
        }
        if(!StringUtil.isEmpty(conUser.getEmail()) && !conUser.getEmail().equals(selectConUser.getEmail())) {
            updateConUser.setEmail(conUser.getEmail());
            flag = true;
        }
        if(!StringUtil.isEmpty(conUser.getPhoneNum()) && !conUser.getPhoneNum().equals(selectConUser.getPhoneNum())) {
            updateConUser.setPhoneNum(conUser.getPhoneNum());
            flag = true;
        }
        if(!StringUtil.isEmpty(conUser.getType()) && !conUser.getType().equals(selectConUser.getType())) {
            updateConUser.setType(conUser.getType());
            flag = true;
        }
        if(!StringUtil.isEmpty(conUser.getRemark()) && !conUser.getRemark().equals(selectConUser.getRemark())) {
            updateConUser.setRemark(conUser.getRemark());
            flag = true;
        }

        //7.判断是否可以调用数据库
        if(flag == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //8.调用数据库
        int row = conUserMapper.updateByPrimaryKeySelective(updateConUser);

        //9.判断是否更新成功
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        //1.参数校验
        if(id == null || id <= 0 || StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.根据id查询用户信息
        ConUser conUser = conUserMapper.selectByPrimaryKey(id);

        //3.判断用户是否存在
        if(conUser == null || conUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //4.判断输入的旧密码是否与表中保存的一致
        String oldEncryptPassword = MD5Util.md5(oldPassword,conUser.getSalt());
        if(!oldEncryptPassword.equalsIgnoreCase(conUser.getPassword())) {
            log.warn(ResultCode.FAILED_OLD_PASSWORD.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_OLD_PASSWORD));
        }

        //5.对新密码进行MD5加密
        String newSalt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5(newPassword,newSalt);

        //6.更新修改内容
        ConUser updateCon = new ConUser();
        updateCon.setId(conUser.getId());
        updateCon.setSalt(newSalt);
        updateCon.setPassword(encryptPassword);
        Date date = new Date();
        updateCon.setUpdateState(date);

        //7.调用数据库
        int row = conUserMapper.updateByPrimaryKeySelective(updateCon);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

    }

    @Override
    public List<ConUser> selectAllInfo() {

        //1.调用数据库
        List<ConUser> conUsers = conUserMapper.selectAllInfo();

        //返回结果
        return conUsers;

    }

    @Override
    public void updateDeleteStateByUsername(String username) {
        //1.非空校验
        if(StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        //2.根据用户名查询用户
        ConUser conUser = conUserMapper.ConselectByUsername(username);
        if(conUser == null || conUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //3.封装修改对象
        ConUser updateCon = new ConUser();
        updateCon.setId(conUser.getId());
        updateCon.setDeleteState((byte) 1);
        updateCon.setUpdateState(new Date());

        //4.调用数据库
        int row = conUserMapper.updateByPrimaryKeySelective(updateCon);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public void createCon(ConUser conUser) {

        //1.参数校验
        if(conUser == null || StringUtil.isEmpty(conUser.getUsername())
         || StringUtil.isEmpty(conUser.getPassword()) || StringUtil.isEmpty(conUser.getNickname())
        || StringUtil.isEmpty(conUser.getGender()) || StringUtil.isEmpty(conUser.getSalt())
        || StringUtil.isEmpty(conUser.getType())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.根据用户名查询用户是否存在
        ConUser selectCon = conUserMapper.ConselectByUsername(conUser.getUsername());
        if(selectCon != null) {
            log.warn(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //3.设置默认值
        conUser.setDeleteState((byte) 0);
        conUser.setArticleCount(0);
        conUser.setIsReign((byte) 1);
        conUser.setIsOnline((byte) 0);
        conUser.setRemark("");
        Date date = new Date();
        conUser.setCreateState(date);
        conUser.setUpdateState(date);

        //4.动态插入信息
        int row = conUserMapper.insertSelective(conUser);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        log.info("新增用户成功");

    }
}
